package com.corn.zk.register;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/12 10:12
 */
@Slf4j
public class MyRegisterServer {

    public MyRegisterServer(String zkServers) {
        this.zkServers = zkServers;
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        MyRegisterServer registerServer = new MyRegisterServer(args[0]);
        registerServer.init();
        registerServer.getServerList();
        registerServer.doBusiness();
    }

    private ZooKeeper zk;

    private final String zkServers;

    private final int sessionTimeout = 2000;

//    private List<String> clientList = new ArrayList<>();

    private final String registerZkPath = "/servers";

    private final CountDownLatch awaitZkConnectedLatch = new CountDownLatch(1);

    private void init() throws IOException, KeeperException, InterruptedException {
        zk = new ZooKeeper(zkServers, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    awaitZkConnectedLatch.countDown();
                }
            }
        });
        // 等待链接建立成功
        if (zk.getState() == ZooKeeper.States.CONNECTING) {
            awaitZkConnectedLatch.await();
        }
        Stat exists = zk.exists(registerZkPath, false);
        if (exists == null) {
            zk.create(registerZkPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    }

    private void getServerList() throws KeeperException, InterruptedException {
        List<String> children = zk.getChildren(registerZkPath, new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {
                getServerList();
            }
        });
        System.out.println("======================");
        log.info("节点信息clientList:{}", String.join(",", children));
        children.forEach(child -> {
            try {
                log.info("节点名:{} 节点值:{}", child, new String(zk.getData(registerZkPath + "/" + child, false, null)));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    private void doBusiness() {
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
